package com.jojo.bubble.controller;

import com.jojo.bubble.entity.Admin;
import com.jojo.bubble.entity.Logs;
import com.jojo.bubble.service.AdminService;
import com.jojo.bubble.common.domain.AjaxResult;
import com.jojo.bubble.service.LogsService;
import com.jojo.bubble.utils.CaptchaUtil;
import com.jojo.bubble.utils.ImageFileUtil;
import com.jojo.bubble.utils.MD5Util;
import com.jojo.bubble.utils.QiniuUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.ObjectUtils;
import com.jojo.bubble.common.enums.JsonResultEnum;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Objects;

/**
 * 管理员(Admin)表控制层
 *
 * @author jojo
 * @since 2023-07-21 04:47:25
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    /**
     * 服务对象
     */
    @Resource
    private AdminService adminService;
    @Resource
    private LogsService logsService;
    /**
     * @desc: 登录
     * @param: [username, password, request, response]
     * @return: com.jojo.ocr_car.common.domain.AjaxResult
     * @date: 2022/11/21 17:55
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String username, String password, String token, HttpServletRequest request, HttpServletResponse response) throws UnknownHostException {
//        if (!CaptchaUtil.ver(token, request)) {
////            CaptchaUtil.clear(request);  // 清除session中的验证码
//            return AjaxResult.error("验证码错误");
//        }
        String remember = request.getParameter("remember");
        Admin user = adminService.getRecordByName(username);
        InetAddress addr = InetAddress.getLocalHost();
        String ip = addr.getHostAddress();//获得本机IP
        String address = addr.getHostName();//获得本机名称
        Logs logs = new Logs();
        logs.setIp(ip);
        logs.setHostName(address);
        logs.setUsername(username);
        if (ObjectUtils.nullSafeHashCode(user) == 0) {

            logs.setStatus(1);
            logsService.insert(logs);
            return AjaxResult.error(JsonResultEnum.ADMIN_USER_NULL);
        } else if (!MD5Util.string2MD5(password).equals(user.getPassword())) {
            logs.setStatus(1);
            logsService.insert(logs);
            return AjaxResult.error(JsonResultEnum.ADMIN_PASS_ERROR);
        }
        HttpSession session = request.getSession();
        if (remember != null) {
            Cookie cookieUser = new Cookie("username", username);
            Cookie cookiePass = new Cookie("password", password);
            cookiePass.setMaxAge(60 * 60 * 24);
            cookieUser.setMaxAge(60 * 60 * 24);
            response.addCookie(cookieUser);
            response.addCookie(cookiePass);
            session.setAttribute("rememberU", username);
            session.setAttribute("rememberP", password);
        } else {
            session.removeAttribute("rememberU");
            session.removeAttribute("rememberP");
        }

//        AuthUser authUser = new AuthUser();
//        authUser.setAdminId(user.getId());
//        authUser.setStatus(0);
//        List<AuthUser> authUsers = authUserService.getList(authUser);
        logsService.insert(logs);
        session.setAttribute("adminId", user.getId());
        session.setAttribute("agentId", user.getAgentId());
        session.setAttribute("role", user.getRole());
        session.setAttribute("type", user.getType());
        session.setAttribute("admin", user);
//        session.setAttribute("title", authUsers);
        return AjaxResult.successData(user);
    }

    @RequestMapping(value = "/logout")
    public void logout(HttpSession session, HttpServletResponse response) {
        // 移除session
        session.removeAttribute("admin");
        session.removeAttribute("role");
        session.removeAttribute("agentId");
        session.removeAttribute("agentId");
        session.removeAttribute("title");
        // 设置cookie值和时间为空
        Cookie cookie = new Cookie("S_L_ID", "");
        cookie.setValue(null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        try {
            // 跳转到登录页面
            response.sendRedirect("/");
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    @PostMapping("/sysUser/edit")
    public AjaxResult editSysUser(Admin admin) {
        Admin record = adminService.getRecordByName(admin.getUsername());
        if (!ObjectUtils.isEmpty(record) && !Objects.equals(record.getId(), admin.getId())) {
            return AjaxResult.error(JsonResultEnum.USER_EXISTS);
        }

        admin.setPassword(MD5Util.string2MD5(admin.getPassword()));
        adminService.update(admin);

        return AjaxResult.success();
    }

    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult upload(MultipartFile file) throws IOException {
        String url = ImageFileUtil.uploadFile( file);
        return AjaxResult.successData(url);
    }

    @PostMapping("/qiNiu/upload")
    public AjaxResult uploadImg(@RequestParam(value="files",required=false)MultipartFile image) {
        if (image.isEmpty()) {
            return AjaxResult.error(400, "上传文件不能为空");
        }

        try {
            byte[] bytes = image.getBytes();
            //文件名
            String fileName = System.currentTimeMillis() + image.getOriginalFilename();
            System.out.println("fileName:" + fileName);
            //上传工具类
            QiniuUtils qiniuUtil = new QiniuUtils();
            try {
                //使用base64方式上传到七牛云
                String url = qiniuUtil.put64image(bytes, fileName);
                return AjaxResult.successData(url);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error(500, "文件上传发生异常");
            }
        } catch (IOException e) {
            return AjaxResult.error(500, "文件上传发生异常");
        }
    }

    @PostMapping("/qiNiu/delete")
    public AjaxResult deleteOldImage(String oldImage) throws IOException {
        QiniuUtils qiniuUtil = new QiniuUtils();
        qiniuUtil.delete(oldImage);
        return AjaxResult.success();
    }


    @GetMapping("/list")
    public AjaxResult getList(Admin record) {
        List<Admin> adminList = adminService.getList(record);
        return AjaxResult.success(adminList);
    }

    @GetMapping("/info")
    public AjaxResult getInfo(Integer id) {
        Admin admin = adminService.getInfo(id);
        return AjaxResult.success(admin);
    }

    @PostMapping("/insert")
    public AjaxResult insert(Admin record) {
        adminService.insert(record);
        return AjaxResult.success();
    }

    @PostMapping("/update")
    public AjaxResult update(Admin record) {
        Admin admin = adminService.getInfo(record.getId());
        if (ObjectUtils.isEmpty(admin)) {
            return AjaxResult.error(JsonResultEnum.RECORD_NULL);
        }
        adminService.update(record);
        return AjaxResult.success();
    }

    @PostMapping("/delete")
    public AjaxResult delete(int id) {
        adminService.delete(id);
        return AjaxResult.success();
    }


}

